package com.xdf.xzymanagementsystem.controller.system;

import com.xdf.xzymanagementsystem.config.MyUsernamePasswordToken;
import com.xdf.xzymanagementsystem.entity.ResponseResult;
import com.xdf.xzymanagementsystem.entity.SysUser;
import com.xdf.xzymanagementsystem.enums.ResponseEnum;
import com.xdf.xzymanagementsystem.exc.UserLoginErrorException;
import com.xdf.xzymanagementsystem.service.StatusUserService;
import com.xdf.xzymanagementsystem.service.SysUserService;
import com.xdf.xzymanagementsystem.util.MD5Util;
import com.xdf.xzymanagementsystem.util.SessionUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @program: xzy-management-system
 * @description: 登录
 * @author: 张柯
 * @create: 2021-01-03 08:38
 **/
@Controller
@RequestMapping("/system")
public class LoginController {
    @Autowired
    private SessionUtils sessionUtils;
    private SysUserService userService;
    @Value("${server.servlet.context-path}")
    private String contentPath;

    @Autowired
    public void setUserService(SysUserService userService) {
        this.userService = userService;
    }
    @Autowired
    private StatusUserService statusUserService;


    /**
     * 登录用户
     *
     * @param user
     * @return
     */
    @PostMapping("/login")
    @ResponseBody
    public ResponseResult<Void> login(SysUser user) throws Exception {
        if (user == null) throw new UserLoginErrorException("账号密码不能为空!");
        String loginName = user.getLoginName();
        String password = MD5Util.toMD5(user.getLoginPassword());
//        UsernamePasswordToken token = new UsernamePasswordToken(loginName, password);
        MyUsernamePasswordToken token = new MyUsernamePasswordToken(loginName, password,user.getUserPhone());
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);
        } catch (IncorrectCredentialsException e) {
            return ResponseResult.<Void>builder().success(false).message("密码错误！").build();
        } catch (Exception e) {
            return ResponseResult.<Void>builder().success(false).message(e.getMessage()).build();
        }
        Session session = subject.getSession();
        session.touch();

        sessionUtils.setUser();
        // 2022年2月11日 14:38:54 chanchaw 更新用户 online 状态
        statusUserService.updateOnlineStatus(user.getLoginName(),true);// 设置为在线状态
        return ResponseResult.<Void>builder().success(true).message(ResponseEnum.OK.getName()).build();
    }

    /**
     * 登出账号
     *
     * @return
     */
    @PostMapping("/logout")
    @ResponseBody
    public ResponseResult<Void> logOut(HttpServletResponse response) throws IOException {
        if (SecurityUtils.getSubject().isAuthenticated()) {
            // 设置为离线状态
            Object userPK = SecurityUtils.getSubject().getPrincipal();
            Integer userPK1 = Integer.parseInt((String) userPK);
            statusUserService.updateOnlineStatus(userPK1,false);// 设置为在线状态

            // 设置完状态后再退出
            SecurityUtils.getSubject().logout();
        }
        return ResponseResult.<Void>builder().success(true).message(ResponseEnum.OK.getName()).build();
    }
}
